
foreach yr in 11 12 13 14 {

	*Load and process IP claims
	insheet using "$temp\ipclaims`yr'.csv", comma clear
	
	if `yr' == 14 {
		gen hnpi_re = hnpi
		replace hnpi = hnpi_be if hnpi_be != ""
		drop hnpi_be
	}
	
	else {
		drop hnpi_be
		gen hnpi_re = ""
	}
	
	*Keep only patients under age 65
	drop if age_band_cd > 6

	*drop non-GAC discharges
	gen flag = mdc if inlist(mdc, "2", "19", "20", "23")
	replace flag = "0" if flag == ""
	destring flag, replace
	bysort admit_id: egen mdc_check = max(flag)
	drop if mdc_check != 0
	drop flag mdc_check

	*drop observations with no NPI
	gen flag = hnpi != ""
	bysort admit_id: egen max_flag = max(flag)
	drop if max_flag == 0
	drop flag max_flag

	*Keep only admit_ids with inpatient hospital TOBs
	gen tob2 = substr(tob, 1, 2)
	gen flag = inlist(tob2, "11", "12", "18", "41", "85")
	bysort admit_id: egen max_flag = max(flag)
	drop if max_flag != 1
	drop tob2 flag max_flag
		
	*Flag newborns (mdc 15 and admit type 4)
	gen flag = mdc == "15"
	replace flag = 1 if admit_type == 4
	bysort admit_id: egen newborn_flag = max(flag)
	drop flag 
		
	*create ER admit flag
	gen flag = inlist(rvnu_cd, 450, 451, 452, 456, 459, 981)
	bysort admit_id: egen er_flag = max(flag)
		
	keep charge amt_net_paid coins copay deduct calc_allwd z_patid admit_id dstatus fst_admtdt last_dischdt mdc drg ///
	age_band_cd gdr mbr_zip_5_cd prod mkt_sgmnt_cd funding hnpi prov_zip_5_cd hnpi_re ntwrk_ind primary_cov_ind er_flag newborn_flag

	gen fst = date(fst_admtdt, "DMY")
	gen lst = date(last_dischdt, "DMY")
	drop fst_admtdt last_dischdt
	ren (fst lst) (fst_admtdt last_dischdt)
	format fst_admtdt last_dischdt %td
	
	save "$temp\ipclaims`yr'.dta", replace
}

exit



